package net.gz01.wallet.web.controller.org;

import java.util.HashSet;
import java.util.Set;

import com.jfinal.aop.Clear;

import net.gz01.util.ZOMD5;
import net.gz01.wallet.web.auth.Authority;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.interceptors.AuthInterceptor;
import net.gz01.wallet.web.model.Org;
import net.gz01.wallet.web.model.OrgRole;
import net.gz01.wallet.web.model.OrgUser;

@Clear
public class MainController extends BaseController{

	public void loginpage(){
		render("login.html");
	}

	public void home(){
		OrgUser orgUser = (OrgUser) getSession().getAttribute("loginOrgUser");
		Org org = Org.dao.selectByOrgCode(orgUser.getOrgCode());
		setAttr("org", org);
		render("console.html");
	}

	public void login(){
		if(!validateCaptcha("vercode")){
			renderMsg(1, "验证码错误.");
		}else{
			String userName = getPara("username");
			String password = ZOMD5.codeFor(getPara("password"));
			OrgUser loginUser = OrgUser.dao.loginFind(userName, password);
			if(loginUser != null){
				if(loginUser.getEnable() == false){
					renderMsg(2, "用户被禁用");
				}else{
					OrgRole role = OrgRole.dao.findById(loginUser.getRoleId());
					if(role == null){
						renderMsg(3, "无角色用户,无法登录");
					}else {

						getSession().setAttribute("loginOrgUser", loginUser);
						getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_org_zh_CN());
						setAuthAttr(role);
						renderSuccess();
					}
				}
			}else{
				renderFail("用户名/密码错误");
			}
		}
	}

	/**
	 * 将拥有的权限设置到session供标签使用
	 * @param role
	 */
	private void setAuthAttr(OrgRole role){
		//菜单明细url
		String[] split = role.getSourceUrl().split(",");
		Set<String> menuUrl = new HashSet<>();
		for (String temp : split) {
			menuUrl.add(temp);
		}
		getSession().setAttribute("ORG" + Authority.MENU_URL, menuUrl);

		//菜单组
		split = role.getSourceGroup().split(",");
		Set<String> menuGroup = new HashSet<>();
		for (String temp : split) {
			menuGroup.add(temp);
		}
		getSession().setAttribute("ORG" + Authority.MENU_GROUP, menuGroup);

	}

	/**
	 * 获取验证码
	 */
	public void getCaptchaCode(){
		renderCaptcha();
	}


	public void logout(){
		getSession().removeAttribute("loginOrgUser");
		redirect("/org/loginpage");
	}

}
